package LMS.controller;

import LMS.db.BookItemRepository;
import LMS.db.BookRepository;
import LMS.db.RecordRepository;
import LMS.db.RequestRepository;
import LMS.domain.*;
import LMS.domain.body.ShowRecordBody;
import LMS.domain.body.ShowRequestBody;
import LMS.service.*;
import LMS.utils.PaginationSupport;
import org.hibernate.validator.internal.constraintvalidators.PastValidatorForReadableInstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller
@RequestMapping("/borrower")
public class BorrowerController {

    @Resource
    private RequestService requestService;

    @Resource
    private RecordService recordService;

    @Resource
    private BookItemService bookItemService;

    @Resource
    private BookService bookService;

    @Resource
    private UserService userService;

    @RequestMapping(value = "/modifyPassword", method = GET)
    public String modifyPassword(){
        return "/modifyPassword";
    }

    @RequestMapping(value = "/modifyPassword", method = POST)
    public String modifyPassword(@RequestParam(value = "password")String password,HttpSession session){
        UserEntity user = (UserEntity) session.getAttribute("user");
        userService.modifyPassword(password,user.getId());
        return "redirect:/logout";
    }

    /**
     * 加入借书车
     *
     * @param bookItemId
     *      图书实体id
     * @param session
     *      HtpSession
     * @return
     */
    @RequestMapping(value = "/addIntoCart", method = GET)
    public String requestBook(@RequestParam(value = "bookItemId") long bookItemId, HttpSession session) {
        BookItem bookItem = bookItemService.findBookItem(bookItemId);
        BookEntity book = bookService.findOne(bookItem.getBookId());

        List<BookItem> itemList = (List<BookItem>)session.getAttribute("itemList");
        List<String> nameList = (List<String>)session.getAttribute("nameList");
        if(itemList == null ){
            itemList = new ArrayList<BookItem>();
            session.setAttribute("itemList",itemList);
        }
        if(nameList == null){
            nameList = new ArrayList<String>();
            session.setAttribute("nameList",nameList);
        }

        Integer itemCount = (Integer) session.getAttribute("itemCount");
        if (itemCount == null){
            itemCount = new Integer(0);
        }
        //System.out.println(itemCount);
        //如果存在多次加入同一本书的情况
        for(int i = 0;i < itemCount;i++){
            if(nameList.contains(book.getBookName())){
                return "redirect: ../book/bookInfo?bookId=" + bookItem.getBookId();
            }
        }
        itemList.add(bookItem);
        nameList.add(book.getBookName());
//        session.setAttribute("item" + itemCount, bookItem);
//        session.setAttribute("name" + itemCount, book.getBookName());
//        session.setAttribute("itemList",itemList);
//        session.setAttribute("nameList",nameList);
        session.setAttribute("itemCount", itemCount + 1);


        return "redirect: ../book/bookInfo?bookId=" + bookItem.getBookId();
    }

    /**
     *
     *
     * @param bookItemId
     * @param session
     * @return
     */
    @RequestMapping(value = "/deleteFromCart", method = GET)
    public String deleteFromCart(@RequestParam(value = "bookItemId")long bookItemId,HttpSession session) throws Exception {
        BookItem bookItem = bookItemService.findBookItem(bookItemId);
        BookEntity book = bookService.findOne(bookItem.getBookId());
        List<BookItem> itemList = (List<BookItem>)session.getAttribute("itemList");
        List<String> nameList = (List<String>)session.getAttribute("nameList");
        Integer itemCount = (Integer) session.getAttribute("itemCount");
        if (itemCount == null)
            throw new Exception("itemCount有问题");
        if(nameList == null){
            throw new Exception("nameList有问题");
        }
        if (itemList == null){
            throw new Exception("itemList有问题");
        }
        System.out.println(itemCount);
        if(itemList.contains(bookItem)){
            itemList.remove(bookItem);
            nameList.remove(book.getBookName());
        }
        session.setAttribute("itemList",itemList);
        session.setAttribute("nameList",nameList);
        session.setAttribute("itemCount", itemCount - 1 );
//        session.setAttribute("name" + itemCount, book.getBookName());
        return "redirect: borrowingCart";
    }
    /**
     * 查看借书车
     *
     * @return
     */
    @RequestMapping(value = "/borrowingCart", method = GET)
    public String showCart() {
        return "/borrowingCart";
    }



    /**
     * 提交借书请求
     *
     * @param session
     * @return
     */
    @RequestMapping(value = "/commitRequest", method = GET)
    public String commit(HttpSession session) throws Exception {
        UserEntity user = (UserEntity) session.getAttribute("user");
        Integer itemCount = (Integer) session.getAttribute("itemCount");
        List<BookItem> itemList = (List<BookItem>)session.getAttribute("itemList");
        List<String> nameList = (List<String>)session.getAttribute("nameList");
        if (itemCount == null)
            itemCount = new Integer(0);
        if(nameList == null){
            throw new Exception("nameList有问题");
        }
        if (itemList == null){
            throw new Exception("itemList有问题");
        }
        for (int i = 0; i < nameList.size(); i++) {
            BookItem bookItem = itemList.get(i);
            BookItem checkItem = bookItemService.findBookItem(bookItem.getId());
            if(checkItem.isDelete()){
                throw new Exception("图书副本已经被删除，不可借阅");
            }
            requestService.createRequest(user.getAccount(), bookItem.getId());
        }
        session.removeAttribute("itemCount");
        session.removeAttribute("itemList");
        session.removeAttribute("nameList");

        return "/book/commitSuccess";
    }

    /**
     * 获取当前borrower 的借书列表
     *
     * @param session
     * @param model
     */
    @RequestMapping(value = "currentLendingList", method = GET)
    public void currentLending(HttpSession session, Model model) {


        UserEntity user = (UserEntity) session.getAttribute("user");
        List<ShowRecordBody> records = recordService.getBorrowerLendingRecords(user.getAccount());

        model.addAttribute("records", records);

    }

    /**
     * 历史借书记录
     *
     * @param pageNo
     *      页码
     * @param pageSize
     *      容量
     * @param session
     *      HttpSession
     * @param model
     *      控制器model
     * @return
     */
    @RequestMapping(value = "historyLendingList", method = GET)
    public PaginationSupport<ShowRecordBody> historyList(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                                         @RequestParam(value = "pageSize", defaultValue = "8") int pageSize,
                                                         HttpSession session, Model model) {

        UserEntity user = (UserEntity) session.getAttribute("user");
       return recordService.getBorrowerHistoryRecords(user.getAccount(),pageNo,pageSize);
    }

    /**
     * 当前用户的借书请求列表
     *
     * @param pageNo
     *      页码
     * @param pageSize
     *      页码容量
     * @param session
     *      HttpSession
     * @return
     */
    @RequestMapping(value = "requestList", method = GET)
    public PaginationSupport<ShowRequestBody> showBorrowerRequestList(
            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            HttpSession session,Model model) {

        UserEntity user = (UserEntity) session.getAttribute("user");
        List<ShowRequestBody> currentRequestList = requestService.getBorrowerCurrentRequests(user.getAccount());
        model.addAttribute("current",currentRequestList);
        return requestService.getBorrowerRequests(user.getAccount(), pageNo, pageSize);
    }
}
